const jsonwebtoken = require('jsonwebtoken')
const whiteList = ['/api/login']; // 白名单，
module.exports = () => {
 return async (ctx, next) => {
    if (whiteList.includes(ctx.path)) {
      await next()
    } else {
      const token = ctx.request.headers.authorization;
      console.log(token, '我是token----1')
      if (!token) {
        console.log('--------------0-----')
        ctx.body = {
          code: 401,
          msg: '你没有权限啊，小伙伴'
        }
      } else {
        console.log('--------------0-----')
        try{
          const userInfo = jsonwebtoken.verify(token, ctx.app.config.keys)
          ctx.state.user = userInfo;
          console.log(ctx.state.user, 'user-----user')
        }catch(err) {
          console.log(err,'------------------err-------')
          if(e.name == 'TokenExpiredError'){
            ctx.body = {
                code:6,
                mes:'token过期了'
            }
          }
          ctx.throw(err.message)
        }
        await next()
      }
    }
  }
}